// src/store/modules/message.js
import { defineStore } from 'pinia'
import { useUserStore } from '../user/user'

export const useMessageStore = defineStore('message', {
  state: () => ({
    // 聊天会话列表（用于消息列表页的“聊天”标签）
    chatSessions: [],
    // 当前聊天的消息详情（用于聊天详情页）
    currentChatMessages: [],
    currentTargetUserId: null,
    //  未读信息
    unreadMessages: {
      likeUnreadNum: 0,
      commentUnreadNum: 0,
      atUnreadNum: 0,
      fanUnreadNum: 0,
    },
    // 未读信息总数
    totalUnreadNum: 0
  }),
  getters: {
    // 新消息数量
    newMessageNum(state) {
      const chatUnread = state.chatSessions.reduce((acc, cur) => {
        return acc + (cur.unreadCount || 0);
      }, 0);
      const systemUnread =
        state.unreadMessages.likeUnreadNum +
        state.unreadMessages.commentUnreadNum +
        state.unreadMessages.fanUnreadNum;
      return chatUnread + systemUnread;
    },
  },
  actions: {
    // ========== 聊天消息处理 ==========
    // 接收聊天消息（更新会话列表和当前聊天详情）
    addChatMessage(msg) {
      const { fromId: targetUserId } = msg
      // 1. 无论是否当前聊天，都更新会话列表
      this.updateChatSession(msg, targetUserId)

      // 2. 只有当消息属于“当前活跃聊天”时，才更新聊天内容
      if (this.currentTargetUserId === targetUserId) {
        this.currentChatMessages.push(msg)
      }
    },
    // 清空当前聊天消息（切换聊天会话时调用）
    clearCurrentChat() {
      this.currentChatMessages = []
      this.currentTargetUserId = null
    },
    // 发送聊天消息（本地优先更新，再发Socket）
    sendChatMessage(targetUserId, content, img, userNickname) {
      const userStore = useUserStore()
      console.log(userNickname, 'userNickname');
      const userId = userStore.userInfo.userId
      const newMsg = {
        fromId: userId,
        toId: targetUserId,
        content: content,
        createdAt: new Date(),
        userNickname: userNickname || userStore.userInfo.userNickname,
        userAvatar: img || userStore.userInfo.userAvatar,
      }
      console.log('发送的消息:', newMsg);
      console.log(userStore, 'userStore.userInfo');


      // 更新当前聊天消息（若在聊天页）
      if (this.currentTargetUserId === targetUserId) {
        this.currentChatMessages.push(newMsg)
      }
      this.updateChatSession(newMsg, targetUserId)
      // 发送到Socket
      const socket = window.socket
      if (!socket) {
        console.error('window.socket 实例不存在');
        return;
      }
      const doSend = () => {
        socket.emit('sendPrivateLetter', newMsg);
        console.log('消息已发送到服务端');
      };
      if (socket.connected) {
        doSend();
      } else {
        // 未连接：触发重连，并在连接成功后发送
        console.log('Socket 未连接，尝试重连...');
        socket.connect(); // 手动触发连接
        // 监听一次连接成功事件后发送
        socket.once('connect', () => {
          console.log('重连成功，发送消息');
          doSend();
        });
        // 监听连接失败，避免无限等待
        socket.once('connect_error', (err) => {
          console.error('重连失败，无法发送消息：', err.message);
        });
      }
      console.log(newMsg, 'newMsg');

    },
    // 辅助：更新会话列表
    updateChatSession(msg, targetUserId) {
      const sessionIndex = this.chatSessions.findIndex(item => item.targetUserId === targetUserId)
      if (sessionIndex > -1) {
        this.chatSessions[sessionIndex] = {
          ...this.chatSessions[sessionIndex],
          lastMsg: msg.content,
          time: msg.createdAt,
          unreadCount: this.currentTargetUserId === targetUserId
            ? 0 // 如果是当前聊天，未读计数清零
            : this.chatSessions[sessionIndex].unreadCount + 1
        }
        console.log(this.chatSessions[sessionIndex].unreadCount, 'this.chatSessions[sessionIndex]');

      } else {
        this.chatSessions.unshift({
          targetUserId,
          targetUserNickname: msg.userNickname,
          targetUserImg: msg.userAvatar,
          lastMsg: msg.content,
          time: msg.createdAt,
          unreadCount: this.currentTargetUserId === targetUserId ? 0 : 1,
          type: 'chat'
        })
      }
    },
    // 初始化当前聊天的历史消息（进入聊天页时调用）
    initCurrentChat(targetUserId, historyMessages) {
      this.currentTargetUserId = targetUserId // 标记当前活跃聊天
      this.currentChatMessages = historyMessages // 加载历史消息
      // 清空该会话未读计数
      this.clearUnreadCount(targetUserId)
    },
    // 清空会话的未读计数（切换到该会话时调用）
    clearUnreadCount(targetUserId) {
      const sessionIndex = this.chatSessions.findIndex(item => item.targetUserId === targetUserId)
      if (sessionIndex > -1) {
        this.chatSessions[sessionIndex].unreadCount = 0
      }
    },
    // 接收点赞消息（更新会话列表和当前聊天详情）
    addLikeMessage(num) {
      console.log('点赞未读消息数', num);
      this.unreadMessages.likeUnreadNum = num
    },
    // 接收评论消息（更新会话列表和当前聊天详情）
    addCommentMessage(num) {
      console.log('评论未读消息数', num);
      this.unreadMessages.commentUnreadNum = num
    },
    // 接收@消息（更新会话列表和当前聊天详情）
    addAtMessage(num) {
      console.log('@未读消息数', num);
      this.unreadMessages.atUnreadNum = num
    },
    // 接收关注消息（更新会话列表和当前聊天详情）
    addFanMessage(num) {
      console.log('关注未读消息数', num);
      this.unreadMessages.fanUnreadNum = num
    },
    // 改变未读信息总数
    changeTotalUnreadNum(num) {
      this.totalUnreadNum = num
      console.log('未读信息总数', this.totalUnreadNum);

    }
  }
})
